package com.dx.mes.web;

import com.dx.mes.facade.process.tx.Fspboxchgdef.SortPo;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;

@Controller
public class FspboxchgdefController {
    @RequestMapping(value = "/download.do")
    public String downloadFile(@RequestParam("fileName") String fileName,
                               HttpServletRequest request, HttpServletResponse response) {
        if (fileName != null) {
            File file = new File("E:/" + fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition",
                        "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

   /* @Resource
    //private FspboxchgdefService fspboxchgdefService;*/

    @RequestMapping(value = "/exportExcel.do" ,method= RequestMethod.POST,headers="content-type=application/json")
    public String exportExcel(@RequestBody SortPo[] sortPoList,
                            HttpServletRequest request ,HttpServletResponse response) throws Exception{
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wkb = new HSSFWorkbook();
        //建立新的sheet对象（excel的表单）
        HSSFSheet sheet=wkb.createSheet("Sorter");
        //在sheet里创建第一行，参数为行索引(excel的行)，可以是0～65535之间的任何一个
        HSSFRow row1=sheet.createRow(0);
        //创建单元格（excel的单元格，参数为列索引，可以是0～255之间的任何一个
        HSSFCell cell=row1.createCell((short)0);
        //设置单元格内容
        cell.setCellValue(new HSSFRichTextString("源箱号"));
        HSSFCell cell2 =row1.createCell((short)1);
        cell2.setCellValue(new HSSFRichTextString("源子格位"));
        HSSFCell cell3 =row1.createCell((short)2);
        cell3.setCellValue(new HSSFRichTextString("目标箱号"));
        HSSFCell cell4 =row1.createCell((short)3);
        cell4.setCellValue(new HSSFRichTextString("目标子格位"));
        HSSFCell cell5 =row1.createCell((short)4);
        cell5.setCellValue(new HSSFRichTextString("备注"));

        for(int i = 1 ; i < sortPoList.length + 1;i++){
            SortPo sortPo = sortPoList[i-1];
            HSSFRow row2=sheet.createRow(i);
            row2.createCell((short)0).setCellValue(new HSSFRichTextString(sortPo.getFr_box_id_fk()));
            row2.createCell((short)1).setCellValue(new HSSFRichTextString(sortPo.getFr_slot_no_fk()));
            row2.createCell((short)2).setCellValue(new HSSFRichTextString(sortPo.getTo_box_id_fk()));
            row2.createCell((short)3).setCellValue(new HSSFRichTextString(sortPo.getTo_slot_no_fk()));
            row2.createCell((short)4).setCellValue(new HSSFRichTextString(sortPo.getEvtNote()));
        }
       /* response.setContentType("multipart/form-data");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=Sorter.xls");
        OutputStream ouputStream = response.getOutputStream();
        wkb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();*/

       /* OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=Sorter.xls");
        response.setContentType("application/msexcel");
        wkb.write(output);
        output.close();
        return null;*/
        String filePath= request.getSession().getServletContext().getRealPath("/excel/");
        filePath = URLDecoder.decode(filePath, "UTF-8");
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //excel路径
        String excelName = String.valueOf(System.currentTimeMillis());
        //String excelPath = request.getSession().getServletContext().getRealPath("/excel/"+excelName+".xls");
        //FileOutputStream output = new FileOutputStream(excelPath);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wkb.write(baos);
        baos.flush();
        baos.close();
        response.reset();
        response.addHeader("Content-Disposition", "attachment;filename=" + excelName + ".xls");
        response.addHeader("Content-Length", String.valueOf(baos.size()));
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.getOutputStream().write(baos.toByteArray());
        //String path="excel/"+excelName+".xls";
        return "success";
    }


   /* @RequestMapping(value = "/upload.do")
    @ResponseBody
    public List<String> upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file,
                               Model model, HttpServletResponse response, HttpServletRequest request) throws IOException, ServletException {
        String filename = file.getOriginalFilename();
        InputStream fileInputStream = file.getInputStream();
        //4,存入数组
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            boolean is03Excel = filename.matches("^.+\\.(?i)(xls)$");
            //1、读取工作簿
            Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
            //2、读取工作表
            Sheet sheet = workbook.getSheetAt(0);

            //3、读取行
            if (sheet.getPhysicalNumberOfRows() > 2) {
                for (int k = 1; k < sheet.getPhysicalNumberOfRows(); k++) {
                    //4、读取单元格
                    Row row = sheet.getRow(k);
                    Cell cell0 = row.getCell(0);
                    arrayList.add(String.valueOf(cell0.getNumericCellValue()));
                }
            }
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrayList;
    }*/
}
